package com.ml4ai.backend.services.mappers;

import com.ml4ai.backend.consts.Const;
import com.ml4ai.backend.domain.Site;
import com.ml4ai.backend.dto.SiteDTO;
import com.ml4ai.backend.repository.SiteRepository;
import com.ml4ai.backend.utils.Bean2Bean;
import com.ml4ai.backend.utils.PropertyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by uesr on 2018/9/10.
 */
@Component
public class SiteMapper extends BaseMapper<Site, SiteDTO> {

    @Autowired
    SiteRepository siteRepository;

    @Override
    public Site newEntity() {
        return new Site();
    }

    @Override
    public SiteDTO newDTO() {
        return new SiteDTO();
    }

    @Override
    public Site find(Long id) {
        return siteRepository.findOne(id);
    }

    @Override
    public void entity2dto(Site entity, SiteDTO dto) {
        new Bean2Bean().addPropMapper(
                new PropertyMapper<>("parent", this::e2d),
                new PropertyMapper<>("parent.id", "parentId")
        ).copyProperties(entity, dto);
    }

    @Override
    public void dto2entity(SiteDTO dto, Site entity) {
        new Bean2Bean().addExcludeProp(Const.getNotCopyAuditFields()).addExcludeProp("parent").copyProperties(dto, entity);
        Long parentId = Bean2Bean.getFirstNoNullVal(dto, "parentId", "parent.id");
        if (parentId != null) {
            entity.setParent(siteRepository.findOne(parentId));
        } else {
            entity.setParent(null);
        }
    }
}
